<template>
  <div class="parkAddWrap">
    <div class="pageTableInner">
      <el-form :model="ruleFormAdd" ref="ruleFormAdd" :rules="rulesAdd" label-width="75px" class="demo-ruleForm">
        <div class="infoSearchWrap" style="padding: 20px 20px 0px 20px;">
          <div class="infoSearchOne" style="margin-bottom: 0px;">
            <el-row :gutter="24">
              <el-col :span="5">
                <div class="searchWrap" >
                  <el-form-item label="停放区编码:" prop="areaNo" label-width="90px" :rules="[{ 'required': true, 'message': '请输入停放区编码', 'trigger': 'blur' }]">
                    <el-input style="width: 100%;" size="mini" clearable v-model="ruleFormAdd.areaNo" auto-complete="off" :maxlength="10" placeholder="停放区编码" :disabled="true"></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="searchWrap">
                  <el-form-item style="display: inline-block;" label="泊位容量:" prop="parkValue" :rules="[{ 'required': true, 'message': '请输入泊位容量', 'trigger': 'blur' }]">
                  <span class="searchInputFont" style="width: 100%;">
                    <el-input size="mini" v-model="ruleFormAdd.parkValue" auto-complete="off" placeholder="泊位容量(辆)" :disabled="!ruleFormAdd.edit"></el-input>
                   </span>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="searchWrap">
                  <el-form-item style="display: inline-block;" label="预警阈值:" prop="alarmValue" :rules="[{ 'required': true, 'message': '请输入预警阈值', 'trigger': 'blur' }]">
                  <span class="searchInputFont" style="width: 100%;">
                    <el-input size="mini" v-model="ruleFormAdd.alarmValue" auto-complete="off" placeholder="阈值(辆)" :disabled="!ruleFormAdd.edit"></el-input>
                   </span>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="searchWrap">
                  <el-form-item label="状态:" label-width="50px" prop="areaStatus" :rules="[{ 'required': true, 'message': '请输入区域类型', 'trigger': 'blur' }]">
                    <span class="searchInputFont" style="width: 100%;">
                      <el-select v-model="ruleFormAdd.areaStatus" size="mini" clearable placeholder="区域类型" :disabled="!ruleFormAdd.edit">
                        <el-option
                         v-for="item in options1"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
                        </el-option>
                      </el-select>
                    </span>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="5">
                <div class="searchWrap">
                  <el-form-item style="display: inline-block;" label="详细地址:" prop="areaAddress" :rules="[{ 'required': true, 'message': '请输入详细地址', 'trigger': 'blur' }]">
                  <span class="searchInputFont" style="width: 100%;">
                    <el-input size="mini" v-model="ruleFormAdd.areaAddress" auto-complete="off" placeholder="" :disabled="!ruleFormAdd.edit"></el-input>
                   </span>
                  </el-form-item>
                </div>
              </el-col>
              <div style="float: right;margin-right: 10px;margin-top: 3px;">
                <el-button v-show="ruleFormAdd.edit" type="primary" size="mini" @click="submitForm('ruleFormAdd')">确认</el-button>
              </div>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="6">
                <div class="searchWrap">
                  <el-form-item style="display: inline-block;width: 180px;" label="行政区域:" prop="district" :rules="[{ 'required': true, 'message': '请选择行政区', 'trigger': 'blur' }]">
                    <span class="searchInputFont" style="width: 100%;">
                      <el-select v-model="ruleFormAdd.district" @change="changeDistrict(ruleFormAdd.district)" size="mini" clearable placeholder="行政区" :disabled="true">
                        <el-option
                          v-for="item in $store.state.districtData"
                          :key="item.id"
                          :label="item.regionName"
                          :value="item.id">
                        </el-option>
                      </el-select>
                    </span>
                  </el-form-item>
                  <el-form-item style="display: inline-block;" label-width="0px" prop="street" :rules="[{ 'required': true, 'message': '请选择街道', 'trigger': 'blur' }]">
                    <span class="searchInputFont" style="width: 62%;">
                    <el-select @change="checkstreet(ruleFormAdd.street)" v-model="ruleFormAdd.street" size="mini" clearable placeholder="街道" :disabled="true">
                      <el-option
                        v-for="item in streetData"
                        :key="item.id"
                        :label="item.regionName"
                        :value="item.id">
                      </el-option>
                    </el-select>
                    </span>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="3">
                <div class="searchWrap">
                  <el-form-item style="display: inline-block;" label="长:" prop="areaLength" :rules="[{ 'required': true, 'message': '请输入长', 'trigger': 'blur' }]">
                  <span class="searchInputFont" style="width: 100%;">
                    <el-input size="mini" v-model="ruleFormAdd.areaLength" auto-complete="off" placeholder="米" :disabled="!ruleFormAdd.edit"></el-input>
                   </span>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="3">
                <div class="searchWrap">
                  <el-form-item style="display: inline-block;" label="宽:" prop="areaWide" :rules="[{ 'required': true, 'message': '请输入宽', 'trigger': 'blur' }]">
                  <span class="searchInputFont" style="width: 100%;">
                    <el-input size="mini" v-model="ruleFormAdd.areaWide" auto-complete="off" placeholder="米" :disabled="!ruleFormAdd.edit"></el-input>
                   </span>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="searchWrap">
                  <el-form-item style="display: inline-block;" label="面积:" prop="area" :rules="[{ 'required': true, 'message': '请输入面积', 'trigger': 'blur' }]">
                  <span class="searchInputFont" style="width: 100%;">
                    <el-input size="mini" v-model="ruleFormAdd.area" auto-complete="off" placeholder="平方米" :disabled="!ruleFormAdd.edit"></el-input>
                   </span>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="searchWrap">
                  <el-form-item style="display: inline-block;" label="经纬度:">
                  <span class="searchInputFont" style="width: 100%;">
                    <el-input size="mini" auto-complete="off" :disabled="true" :value="resultShape.length>0 ? (resultShape[0].lat + ','+ resultShape[0].lng): ''"></el-input>
                   </span>
                  </el-form-item>
                </div>
              </el-col>
              <div style="float: right;margin-right: 10px;margin-top: 3px;">
                <router-link style="margin-left: 10px;" to="/parkingArea">
                  <el-button type="primary" @click="$emit('searchRowsInfo')" size="mini">{{ruleFormAdd.edit?'取消':'返回'}}</el-button>
                </router-link>
              </div>
            </el-row>
          </div>
        </div>
      </el-form>
      <div class="mapWrap">
        <div class="containerWrap" ref="mapScreenfull">
          <div class="infoButton">
            <i @click='screenfullMap' style="font-size: 20px;" class="iconfont icon-quanping2"></i>
          </div>
          <div id="container"></div>
          <div class="mapRailButton" v-show="ruleFormAdd.edit">
            <el-button class="editor-btn" type="primary" size="mini" @click="handeldraw(1)">矩 形</el-button>
            <br/><br/>
            <el-button class="editor-btn" type="primary" size="mini" @click="handeldraw(2)">多边形</el-button>
            <br/><br/>
            <el-button class="editor-btn" type="primary" size="mini" @click="handeldraw(0)">清 除</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

  export default {
    props: ["checkInfo"],
    data () {
      return {
        map: "",
        drawingManager: "",
        dioTrue: "",
        value7: "",
        resultShape: [],
        overlays: [],
        markers: [],
        EditPosition: [],
        ruleFormAdd: {
          "street": "",
          district: this.$store.state.userInfo.regionId,
          "areaNo": "",
          "areaType": "0", //0 停放区
          "areaAttribute": "0",
          "parkValue": "",
          "areaStatus": "0",
          "lng": "",
          "lat": "",
          "areaPoints": "[{\"lng\":113.944165,\"lat\":22.529208},{\"lng\":113.944902,\"lat\":22.529208},{\"lng\":113.944902,\"lat\":22.528954},{\"lng\":113.944165,\"lat\":22.528954}]"
        },
        options1: [
          {
            value: '0',
            label: '正常'
          }, {
            value: '1',
            label: '规划中'
          }, {
            value: '2',
            label: '停用'
          }, {
            value: '3',
            label: '废除'
          }],
        rulesAdd: {},
        options: [
          {
            value: '0',
            label: '停放区'
          }, {
            value: '1',
            label: '禁停区'
          }, {
            value: '2',
            label: '严管区域'
          }, {
            value: '3',
            label: '临时严管区域'
          }, {
            value: '4',
            label: '精细化试点管理区域'
          }, {
            value: '5',
            label: '总量控制区域'
          }],
        streetData: [],
      }
    },

    mounted(){

      this.getRailMap()
      document.querySelector(".containerWrap").style.height = document.querySelector(".mapWrap").clientHeight - 20 + "px"
      setTimeout(() => {
        this.changeDistrict(this.ruleFormAdd.district,1)
      }, 100)
    },
    created(){
      this.ruleFormAdd = this.checkInfo
      this.ruleFormAdd.areaStatus = this.checkInfo.areaStatus + ""
      this.EditPosition=JSON.parse(this.ruleFormAdd.areaPoints)
      this.resultShape =JSON.parse(this.ruleFormAdd.areaPoints)
    },

    methods: {
      submitForm(formName) {
        this.getPoint()
        this.ruleFormAdd.areaPoints = JSON.stringify(this.resultShape)
        if (this.resultShape.length == 0) {
          this.$message({
            type: 'warning',
            message: "请在地图上画区域"
          });
          this.getPoint()
          return
        }
        let latAll = 0, lngAll = 0
        this.resultShape.forEach(item => {
          latAll += item.lat
          lngAll += item.lng
        })
        this.ruleFormAdd.lng = (lngAll / this.resultShape.length).toFixed(7)
        this.ruleFormAdd.lat = (latAll / this.resultShape.length).toFixed(7)
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.axios.post(process.env.API_HOST + 'area/updateGovArea', this.ruleFormAdd)
              .then(response => {
                let result = response.data
                if (result.code == 200) {
                  this.$message({
                    type: 'success',
                    message: '修改成功!'
                  });
                  this.$emit("searchRowsInfo")
                  setTimeout(() => {
                    this.$router.push("/parkingArea")
                  }, 1300)
                }

              })
              .catch(error => {
                console.log(error);
              });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },

      getPoint(){
        var arr = [];
        if (this.overlays.length > 1) {
          this.$message({
            type: 'warning',
            message: "地图区域单次只能增加1个"
          });
          this.dioTrue = true
        } else {
          this.dioTrue = false
          this.overlays.forEach((item) => {
            item.getPath().forEach((item2) => {
              arr.push({lat: item2.lat, lng: item2.lng})
            })
          })
        }
        this.resultShape = arr

      },
      handeldraw(index){
        if (index == 0) {//清除
          this.clearAll()
          this.resultShape = []
        } else if (index == 1) {//矩形
          this.draw(BMAP_DRAWING_RECTANGLE)
        } else if (index == 2) {//多边形
          this.draw(BMAP_DRAWING_POLYGON)
        }
      },
      screenfullMap(){
        if (this.screenfull.enabled) {
          this.screenfull.toggle(this.$refs.mapScreenfull);
        }
      },
      getLocation(name){
        if (name != "") {
          this.map.clearOverlays();
          this.map.centerAndZoom("深圳市" + name, 13);      // 用城市名设置地图中心点
        }
      },
      editMap(styleOptions){
        let _this=this
        if(this.EditPosition&&this.EditPosition.length>2){
          var arr=[]
          this.EditPosition.forEach((item)=>{
            arr.push(new BMap.Point(item.lng,item.lat))
          })
          _this.polygon = new BMap.Polygon(arr, styleOptions);  //创建多边形
          this.map.addOverlay(_this.polygon);           //增加多边形
          _this.polygon.enableEditing()
          _this.overlays.push(_this.polygon)
          _this.map.setViewport(_this.polygon.getPath());    //调整视野
        }
      },
      //获取街道
      changeDistrict(district,key){
        if(!district){
          this.ruleFormAdd.street=""
          this.streetData=[]
          return
        }
        this.axios.post(process.env.API_HOST + '/common/selectRegion',{parentId:district})
          .then(response => {
            const result = response.data
            if (result.code == 200) {
              this.streetData = result.result
            }
          })

        //定位
        if(key!=1){
          this.$store.state.districtData.forEach(item=>{
            if (item.id == district && item.regionPoints) {
              this.getBoundary(JSON.parse(item.regionPoints))
            }
          })
        }

      },
      //改变街道
      checkstreet(street){
        if(!this.ruleFormAdd.street){
          this.changeDistrict(this.ruleFormAdd.district)
        }
        this.streetData.forEach(item => {
          if (item.id ==street && item.regionPoints) {
            this.getBoundary(JSON.parse(item.regionPoints))
          }
        })
      },
      //百度提取区域经纬度
      getBoundary(areaPoints) {
        this.clearAll()
        let _this = this, arr = []
        if (areaPoints && areaPoints.length > 2) {
          _this.map.clearOverlays();        //清除地图覆盖物
          areaPoints.forEach((item) => {
            arr.push(new BMap.Point(item.lng, item.lat))
          })
          //              Polyline  Polygon
          _this.ply = new BMap.Polyline(arr, {
            strokeColor: "#3975FE",    //边线颜色。
            fillColor: "white",      //填充颜色。当参数为空时，圆形将没有填充效果。
            strokeWeight: 1,       //边线的宽度，以像素为单位。
            strokeOpacity: 1,    //边线透明度，取值范围0 - 1。
            fillOpacity: 1,      //填充的透明度，取值范围0 - 1。
            strokeStyle: 'solid' //边线的样式，solid或dashed。
          });  //创建多边形

          _this.map.addOverlay(_this.ply);  //添加覆盖物
          _this.map.setViewport(_this.ply.getPath());    //调整视野

        }

      },
      getRailMap(){
        let _this = this
        _this.map = new BMap.Map("container", {
          enableMapClick: false,
          minZoom: 10,
          maxZoom: 19
        });          // 创建地图实例
        let pointOne = new BMap.Point(114.064552, 22.548457)

        _this.map.centerAndZoom(pointOne, 20);             // 初始化地图，设置中心点坐标和地图级别
        _this.map.enableScrollWheelZoom(); // 允许滚轮缩放

        _this.map.addControl(new BMap.OverviewMapControl());
        _this.map.addControl(new BMap.NavigationControl());  //添加默认缩放平移控件
        this.map.addControl( new BMap.ScaleControl({anchor: BMAP_ANCHOR_BOTTOM_RIGHT}));
//        _this.map.addOverlay(new BMap.Marker(pointOne))

//        var overlays = [];
        var overlaycomplete = function (e) {
          _this.overlays.push(e.overlay);
          _this.getPoint()
        };
        var styleOptions = {
          strokeColor: "#3975FE",    //边线颜色。
          fillColor: "#A9CDE5",      //填充颜色。当参数为空时，圆形将没有填充效果。
          strokeWeight: 1,       //边线的宽度，以像素为单位。
          strokeOpacity: 0.8,    //边线透明度，取值范围0 - 1。
          fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
          strokeStyle: 'solid' //边线的样式，solid或dashed。
        }

        //实例化鼠标绘制工具
        _this.drawingManager = new BMapLib.DrawingManager(_this.map, {
          isOpen: false, //是否开启绘制模式
          drawingToolOptions: {
            anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
            offset: new BMap.Size(5, 5), //偏离值
          },
          polygonOptions: styleOptions, //多边形的样式
          rectangleOptions: styleOptions //矩形的样式
        });

        //添加鼠标绘制工具监听事件，用于获取绘制结果
        _this.drawingManager.addEventListener('overlaycomplete', overlaycomplete);
        _this.editMap(styleOptions)

      },
      draw(type){
        this.drawingManager.open();
        this.drawingManager.setDrawingMode(type);

      },
      clearAll () {
        for (var i = 0; i < this.overlays.length; i++) {
          this.map.removeOverlay(this.overlays[i]);
        }
        this.overlays.length = 0
        this.drawingManager.close()
      },


    },
    watch: {
      /*lngLat(){
       this.getRailMap()
       }*/
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">
  @import "../../../common/stylus/mixin.styl"
  .parkAddWrap
    page1()
    background-color #EFEEF3
    .mapWrap
      position absolute
      top 120px
      left 0px
      right 0px
      bottom 0px
      padding 10px
      box-sizing border-box
      background-color white
      border-radius 5px
      .containerWrap
        height: 100%;
        width: 100%;
        margin 0px auto;
        position: relative;
        .infoButton
          font-size: 16px;
          color: $co1;
          position: absolute;
          top: 10px;
          right: 10px;
          z-index 5
          opacity: 0;
          .iconfont
            display: inline-block;
            font-size: 20px;
            cursor pointer
        #container
          height: 100%;
          width: 100%;
        .mapRailButton
          position: absolute;
          top: 180px;
          left: 12px;
      &:hover .infoButton
        opacity: 1;

</style>
